package com.swn.common.util;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.junit.Test;

import sun.misc.BASE64Encoder;

public class FastDFSUtil {

	    public String conf_filename = StaticParam.getClassesPath()+"fdfs_conf.properties"; 

	    public String[] uploadInput(byte[] b,String type) {

	        try { 
	            ClientGlobal.init(conf_filename);
	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;
	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            
	            String fileIds[] = null;
	            if("voice".equals(type)){
	            	fileIds = storageClient.upload_appender_file(b, "wav", null);
	            }else if("video".equals(type)){
	            	fileIds = storageClient.upload_appender_file(b, "mp4", null);
	            }else{
	            	fileIds = storageClient.upload_appender_file(b, "jpg", null);
	            }
	            
	            //System.out.println(fileIds.length); 
	            //System.out.println("长度" + fileIds[0]); 
	            //System.out.println("组名: " + fileIds[1]);
	            return fileIds;

	        } catch (FileNotFoundException e) { 
	            e.printStackTrace(); 
	        } catch (IOException e) { 
	            e.printStackTrace(); 
	        } catch (MyException e) { 
	            e.printStackTrace(); 
	        } 
	        return null;
	    }
	    
	    
	    //上传音频
	    public String[] uploadVoice(byte[] b) {

	        try { 
	            ClientGlobal.init(conf_filename);
	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;
	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            
	            String fileIds[] = storageClient.upload_appender_file(b, "wav", null);
	            
	            //System.out.println(fileIds.length); 
	            //System.out.println("长度" + fileIds[0]); 
	            //System.out.println("组名: " + fileIds[1]);
	            return fileIds;

	        } catch (FileNotFoundException e) { 
	            e.printStackTrace(); 
	        } catch (IOException e) { 
	            e.printStackTrace(); 
	        } catch (MyException e) { 
	            e.printStackTrace(); 
	        } 
	        return null;
	    }
	    
	    
	    public static byte[] toByteArray(InputStream input) throws IOException {
	        ByteArrayOutputStream output = new ByteArrayOutputStream();
	        byte[] buffer = new byte[4096];
	        int n = 0;
	        while (-1 != (n = input.read(buffer))) {
	            output.write(buffer, 0, n);
	        }
	        return output.toByteArray();
	    }
	    
	    
	    
	    @Test 
	    public void testDownload() {
	        try {
	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            byte[] b = storageClient.download_file("group1", "M00/00/00/wKgCkVjGutuEUiEgAAAAADTJWbg848.png"); 
	            //System.out.println(b); 
	            IOUtils.write(b, new FileOutputStream("e:/"+UUID.randomUUID().toString()+".png"));
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	    }
	   
	    
	    
	    @Test 
	    public void testGetFileInfo(){ 
	        try { 
	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            FileInfo fi = storageClient.get_file_info("group1", "M00/00/00/wKgCkVjGPJuAYHxrAADyHMOytp4450.jpg"); 
	           /* System.out.println(fi.getSourceIpAddr()); 
	            System.out.println(fi.getFileSize()); 
	            System.out.println(fi.getCreateTimestamp()); 
	            System.out.println(fi.getCrc32()); */
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	    } 
	    
	    
	    
	    @Test 
	    public void testGetFileMate(){ 
	        try { 
	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            NameValuePair nvps [] = storageClient.get_metadata("group1", "M00/00/00/wKgCkVjGPJuAYHxrAADyHMOytp4450.jpg"); 
	            /*for(NameValuePair nvp : nvps){ 
	                System.out.println(nvp.getName() + ":" + nvp.getValue()); 
	            } */
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	    } 
	    
	    
	    
	    @Test 
	    public void testDelete(){ 
	        try { 
	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, 
	                    storageServer); 
	            int i = storageClient.delete_file("group1", "M00/00/00/wKgCkFjGAryATqQUAADyHMOytp4619.jpg"); 
	           // System.out.println( i==0 ? "删除成功" : "删除失败:"+i); 
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	    }
	    
	    
	    
	    
	    
	    /*
		 * 得到上传form内容列表
		 */
		public List<FileItem> getFileItemList(HttpServletRequest request) throws Exception {
			// 使用Apache文件上传组件处理文件上传步骤：
			// 1、创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置工厂的缓冲区的大小，当上传的文件大小超过缓冲区的大小时，就会生成一个临时文件存放到指定的临时目录当中。
			factory.setSizeThreshold(1024 * 200);// 设置缓冲区的大小为1M，如果不指定，那么缓冲区的大小默认是10KB
			// 设置上传时生成的临时文件的保存目录
			// factory.setRepository(tmpFile);
			// 2、创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 监听文件上传进度
			upload.setProgressListener(new ProgressListener() {
				public void update(long pBytesRead, long pContentLength, int arg2) {
					// System.out.println("文件大小为：" + pContentLength + ",当前已处理：" + pBytesRead);
				}
			});
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");
			// 3、判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照传统方式获取数据
				return null;
			}
			// 设置上传单个文件的大小的最大值，目前是设置为1024*1024*100字节，也就是100MB
			upload.setFileSizeMax(1024 * 1024 * 100);
			// 设置上传文件总量的最大值，最大值=同时上传的多个文件的大小的最大值的和，目前设置为100MB
			upload.setSizeMax(1024 * 1024 * 1000);
			// 4、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
			List<FileItem> list = upload.parseRequest(request);
			return list;
		}
		
		
		
	    
		/**
		 * 得到文件上传流
		 * 
		 * @return
		 */
		public InputStream getUpStream(List<FileItem> list) throws Exception {
			InputStream in = null;
			for (FileItem item : list) {
				// 表单中是文件的参数
				if (!item.isFormField()) {
					// 获取item中的上传文件的输入流
					in = item.getInputStream();
					return in;
				}
			}
			return in;
		}
	    
	    
	    
	    
	    public byte[] testDownloadByte(String [] arg) {
	        try {

	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            byte[] b = storageClient.download_file(arg[0], arg[1]); 
//	            System.out.println(b); 
	            IOUtils.write(b, new FileOutputStream("e:/"+UUID.randomUUID().toString()+".jpg"));
	            return b;
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	        return null;
	    }
	    
	    
	    
	    public String testDownloadByteStr(String [] arg) {
	        try {

	            ClientGlobal.init(conf_filename);

	            TrackerClient tracker = new TrackerClient(); 
	            TrackerServer trackerServer = tracker.getConnection(); 
	            StorageServer storageServer = null;

	            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
	            byte[] b = storageClient.download_file(arg[0], arg[1]); 
	            return byteToBase64(b);
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } 
	        return null;
	    }
	    String byteToBase64(byte[] b){
	    	BASE64Encoder encode = new BASE64Encoder();
	    	 String base64 = encode.encode(b);
	    	return base64;
	    }
}
